package com.gonfre.quientelo;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gc.materialdesign.utils.Utils;
import com.gc.materialdesign.widgets.Dialog;

import java.util.ArrayList;

import util.AsyncRequest;
import util.AutocompleteCustomArrayAdapter;
import util.CustomAutoCompleteTextChangedListener;
import util.CustomAutoCompleteView;
import util.DataBaseManager;
import util.MyDBObject;
import util.MyDataBase;
import util.MyFieldObject;
import util.MyParameters;
import util.Response;
import util.Tools;


public class RegisterSellerActivity extends MyActivity {

    /*
     * Change to type CustomAutoCompleteView instead of AutoCompleteTextView
     * since we are extending to customize the view and disable filter
     * The same with the XML view, type will be CustomAutoCompleteView
     */

    /*public CustomAutoCompleteView myAutoComplete;
    public ArrayAdapter<MyDBObject> myAdapter;
    public MyDataBase dbLocations;*/

    public String selectedCategories = "";
    public String selectedCategoriesName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_seller);
        myAutoCompletes = new ArrayList<CustomAutoCompleteView>();
        myAdapters = new ArrayList <ArrayAdapter<MyDBObject>> ();
        try{
            // Sincronizar Items
            DataBaseManager dbm = new DataBaseManager(this);
            dbm.syncLocation();
            dbm.syncCategory();

            // Inicializar Campo Ubicacion
            initEditTextLocation();
            // Inicializar Campo Categorias
            initSpinnerCategories();

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initEditTextLocation(){
            DataBaseManager dbm = new DataBaseManager(this);
            String table = this.getString(R.string.table_ubicacion);
            String sql_table = this.getString(R.string.sql_ubicacion);
            dbLocations = new util.MyDataBase(this, dbm, table, sql_table);
            final int j = 0;

            //myAutoComplete = (CustomAutoCompleteView) findViewById(R.id.editTextLocation);
            myAutoCompletes.add((CustomAutoCompleteView) findViewById(R.id.editTextLocation));

            //myAutoComplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            myAutoCompletes.get(j).setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View arg1, int pos, long id) {

                    RelativeLayout rl = (RelativeLayout) arg1;
                    TextView tv = (TextView) rl.getChildAt(0);

                    myAutoCompletes.get(j).setText(getShortLocationName(tv.getText().toString()));
                    myAutoCompletes.get(j).setItemId("" + tv.getId());
                    Log.i("Trace RegisterSellerActivity 'setOnItemClickListener' tv.getId()", ""+tv.getId());
                }

            });

            // add the listener so it will tries to suggest while the user types
            myAutoCompletes.get(j).addTextChangedListener(new CustomAutoCompleteTextChangedListener(this, j));

            // ObjectItemData has no value at first
            MyDBObject[] ObjectItemData = new MyDBObject[0];

            // set the custom ArrayAdapter
            myAdapters.add(new AutocompleteCustomArrayAdapter(this, R.layout.list_view_row, ObjectItemData, null));
            myAutoCompletes.get(j).setAdapter(myAdapters.get(j));
    }

    private void initSpinnerCategories(){
        EditText t4 = (EditText)findViewById(R.id.editTextCategories);
        t4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("Trace RegisterSellerActivity 'setOnItemClickListener'", "editTextCategories");
                Intent intent=new Intent(getApplicationContext(), MultiSelectorActivity.class);
                intent.putExtra("multiSelector", true);
                intent.putExtra("selectedItems", selectedCategories);
                intent.putExtra("selectedItemsName", selectedCategoriesName);
                startActivityForResult(intent, 1);
            }
        });

        ImageView img = (ImageView)findViewById(R.id.buttonCategories);
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("Trace RegisterSellerActivity 'setOnItemClickListener'", "buttonCategories");
                Intent intent=new Intent(getApplicationContext(), MultiSelectorActivity.class);
                intent.putExtra("multiSelector", true);
                intent.putExtra("selectedItems", selectedCategories);
                intent.putExtra("selectedItemsName", selectedCategoriesName);
                startActivityForResult(intent, 1);
            }
        });

    }

    public void buttonSaveOnClick(View w) {
        AsyncRequest req = new AsyncRequest(this);
        Response res = new Response();
        Dialog dialog;

        String pName = getViewValueStr(R.id.editTextName);
        int pLocation = getCustomViewValueInt(R.id.editTextLocation);
        String pLocal = getViewValueStr(R.id.editTextLocalNumber);
        String pPhone = getViewValueStr(R.id.editTextPhone);
        String pEmail = getViewValueStr(R.id.editTextEmail);
        String pPass1 = getViewValueStr(R.id.editTextPassword);
        String pPass2 = getViewValueStr(R.id.editTextConfirmPassword);

        boolean passValidations = true;

        MyParameters p = new util.MyParameters();

        p.add(pName, "Nombre");
        p.add(pLocation, "Ubicacion");
        p.add(pLocal, "Numero Local");
        p.add(pPhone, "Telefono");
        p.add(pEmail, "Email");
        p.add(pPass1, "Password");
        p.add(pPass2, "Confirmar Password");

        String mandatory = p.validateMandatoryData();
        if(mandatory.compareTo("") != 0){
            passValidations = false;
            dialog = new Dialog(this,null, mandatory);
            dialog.show();
            return;
        }

        if(!validatePass(pPass1, pPass2)){
            passValidations = false;
            dialog = new Dialog(this,null, "Verifique el password ingresado.");
            dialog.show();
        }

        if(!validateEmail(pEmail)){
            passValidations = false;
            dialog = new Dialog(this,null, "El Email ingresado no cumple con el formato de correo.");
            dialog.show();
        }

        if(passValidations){
            startProgressBarCircular(R.id.progressBarRegisterSelerLayout);
            res = req.xRegisterSeller(pName, pPhone, pEmail, pPass1, pLocation, selectedCategories, pLocal);
        }
    }

    @Override
    public void onFinishRequest(int type, Response res) {
        stopProgressBarCircular(R.id.progressBarRegisterSelerLayout);
        Dialog dialog = new Dialog(this,null, res.getHeaderResponse().toString() + "-" + res.getHeaderMessage());
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Bundle res = data.getExtras();
                    selectedCategories = res.getString("selectedItems");
                    selectedCategoriesName = res.getString("selectedItemsName");
                    Log.i("Trace RegisterSellerActivity 'onActivityResult' selectedCategories", selectedCategories);
                    Log.i("Trace RegisterSellerActivity 'onActivityResult' selectedCategoriesName", selectedCategoriesName);
                    TextView t0 = (TextView)findViewById(R.id.editTextCategories);
                    t0.setText(selectedCategoriesName);
                }
                break;
        }
    }


}
